package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.cache.J2CacheUtils;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.utils.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "会员验证")
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiUserAuthService userAuthService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ApiAccountService accountService;
    @Autowired
    private ApiUserAccountService userAccountService;
    @Autowired
    ApiSysParameterService sysParameterService;


    /**
     * 发送短信
     */
    @ApiOperation(value = "发送短信")
    @RequestMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(4);
        String msgContent = "您的验证码是：" + sms_code + "，请在页面中提交验证码完成验证。";
        // 发送短信
        String result = "";
        //获取云存储配置信息
        SmsConfig config = sysConfigService.getConfigObject(ConfigConstant.SMS_CONFIG_KEY, SmsConfig.class);
        if (StringUtils.isNullOrEmpty(config)) {
            throw new RRException("请先配置短信平台信息");
        }
        if (StringUtils.isNullOrEmpty(config.getName())) {
            throw new RRException("请先配置短信平台用户名");
        }
        if (StringUtils.isNullOrEmpty(config.getPwd())) {
            throw new RRException("请先配置短信平台密钥");
        }
        if (StringUtils.isNullOrEmpty(config.getSign())) {
            throw new RRException("请先配置短信平台签名");
        }
        try {
            /**
             * 状态,发送编号,无效号码数,成功提交数,黑名单数和消息，无论发送的号码是多少，一个发送请求只返回一个sendid，如果响应的状态不是“0”，则只有状态和消息
             */
            result = SmsUtil.crSendSms(config.getName(), config.getPwd(), phone, msgContent, config.getSign(),
                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "");
        } catch (Exception e) {

        }
        String arr[] = result.split(",");

        if ("0".equals(arr[0])) {
            smsLogVo = new SmsLogVo();
            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
            smsLogVo.setUser_id(loginUser.getUserId());
            smsLogVo.setPhone(phone);
            smsLogVo.setSms_code(sms_code);
            smsLogVo.setSms_text(msgContent);
            userService.saveSmsCodeLog(smsLogVo);
            return toResponsSuccess("短信发送成功");
        } else {
            return toResponsFail("短信发送失败");
        }
    }

    /**
     * 发送短信验证码
     */
    @IgnoreAuth
    @ApiOperation(value = "发送短信验证码")
    @RequestMapping("sendCode")
    public Object sendCode(@RequestParam String phone,@RequestParam String type) throws UnsupportedEncodingException {
        if (StringUtils.isNullOrEmpty(phone)) {
            return toResponsFail("手机号不能为空");
        }
        if (StringUtils.isNullOrEmpty(type)) {
            return toResponsFail("参数不能为空");
        }
        if(type.equals("register")){
            List<UserVo> users = userService.queryByMobile(phone);
            if(users != null && users.size()>0){
                return toResponsFail("手机号码已被注册");
            }
        }else if(type.equals("findPassword")){
            List<UserVo> users = userService.queryByMobile(phone);
            if(users != null){
                if(users.size()==0){
                    return toResponsFail("账户不存在");
                }else if(users.size()>1){
                    return toResponsFail("账户异常");
                }
            }else{
                return toResponsFail("账户不存在");
            }
        }
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = (SmsLogVo)J2CacheUtils.get("code" + phone);
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(6);
        String msgContent = "#code#=" + sms_code;
        String tpl_value = URLEncoder.encode(msgContent, "UTF-8");
        // 发送短信
        String result = null;
        String url = "http://v.juhe.cn/sms/send";
        Map params = new HashMap();
        params.put("mobile",phone);
        params.put("tpl_id","99648");
        params.put("tpl_value",tpl_value);
        params.put("key","545a0e9d4ab06f323b5a50f08d81a3a7");
        try {
            result = SmsUtil.net(url, params, "GET");
            JSONObject object = JSONObject.parseObject(result);
            if(object != null && Integer.parseInt(object.getString("error_code"))==0){
                smsLogVo = new SmsLogVo();
                smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
                smsLogVo.setPhone(phone);
                smsLogVo.setSms_code(sms_code);
                smsLogVo.setSms_text(msgContent);
                J2CacheUtils.put("code" + phone + "", smsLogVo);
                return toResponsObject(0,"短信发送成功",sms_code);
            }else{
                return toResponsFail("短信发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return toResponsFail("短信发送失败");
        }
    }

    /**
     * 获取当前会员等级
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取当前会员等级")
    @RequestMapping("getUserLevel")
    public Object getUserLevel(@LoginUser UserVo loginUser) {
        UserLevelVo userLevel = userService.getUserLevel(loginUser);
        return toResponsSuccess(userLevel);
    }

    /**
     * 绑定手机
     */
    @ApiOperation(value = "绑定手机")
    @RequestMapping("bindMobile")
    public Object bindMobile(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());

        String mobile_code = jsonParams.getString("mobile_code");
        String mobile = jsonParams.getString("mobile");

        if (!mobile_code.equals(smsLogVo.getSms_code())) {
            return toResponsFail("验证码错误");
        }
        UserVo userVo = userService.queryObject(loginUser.getUserId());
        userVo.setMobile(mobile);
        userService.update(userVo);
        return toResponsSuccess("手机绑定成功");
    }

    /**
     * 获取商城用户信息
     *
     * @param loginUser
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "获取商城用户信息")
    @RequestMapping("getShopUser")
    public Object getShopUser(@LoginUser UserVo loginUser) {
        UserVo userVo = userService.getShopUser(loginUser);
        return toResponsSuccess(userVo);

    }

    /**
     * 验证合伙人用户身份
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "验证合伙人用户身份")
    @RequestMapping("updataUser")
    @Transactional
    public Object updataUser(@LoginUser UserVo loginUser) {
        if ( loginUser.getUser_level_id() != null && loginUser.getUser_level_id() < 10 ) {
            return toResponsMsgSuccess("已验证通过");
        }
        if ( loginUser.getUser_level_id() != null && 10 <= loginUser.getUser_level_id()) {
            if(loginUser.getUser_level_id() <100 ){
                return toResponsMsgSuccess("审核中");
            }
            if(loginUser.getUser_level_id() >=100){
                userAuthService.deleteByUserId(loginUser.getUserId());
            }
        }
        JSONObject jsonParams = getJsonRequest();
        if(StringUtils.isNullOrEmpty(jsonParams.getInteger("user_level_id"))){ return toResponsFail("会员身份不能为空");}
        if(StringUtils.isNullOrEmpty(jsonParams.getString("realname"))){ return toResponsFail("真实姓名不能为空");}
        loginUser.setUser_level_id(jsonParams.getInteger("user_level_id"));
        loginUser.setRealname(jsonParams.getString("realname"));
        if(loginUser.getUser_level_id()>10){
            loginUser.setIdcard(jsonParams.getString("idcard"));
            UserAuthVo userAuthVo = new UserAuthVo();
            userAuthVo.setUser_id(loginUser.getUserId());
            userAuthVo.setShopname(jsonParams.getString("shopname"));
            userAuthVo.setArea(jsonParams.getString("area"));
            userAuthVo.setAddr(jsonParams.getString("addr"));
            userAuthVo.setIdcardimgz(jsonParams.getString("idcardimgz"));
            userAuthVo.setIdcardimgf(jsonParams.getString("idcardimgf"));
            userAuthVo.setPermitimg(jsonParams.getString("permitimg"));
            userAuthVo.setShopimg(jsonParams.getString("shopimg"));
            userAuthVo.setIntro(jsonParams.getString("intro"));
            userAuthService.save(userAuthVo);
        }
        userService.update(loginUser);
        return toResponsMsgSuccess("提交成功,请等待审核");
    }

    /**
     * 修改用户信息
     */
    @ApiOperation(value = "修改用户信息")
    @RequestMapping("/update")
    public Object update(@RequestBody UserVo userVo) {
        if(StringUtils.isNullOrEmpty(userVo.getUserId())){ return toResponsFail("账户异常");}
        UserVo userEntity = userService.queryObject(userVo.getUserId());
        if(userEntity == null){return toResponsFail("账户不存在");}
        if(!userEntity.getMobile().equals(userVo.getMobile())){
            return toResponsFail("此处不能修改手机号");
        }
        userService.update(userVo);
        return toResponsMsgSuccess("执行成功");
    }
    /**
     * 获取app版本信息
     */
    @ApiOperation(value = "获取app版本信息")
    @RequestMapping("/appVersion")
    public Object appVersion(@LoginUser UserVo loginUser) {
        Map<String, Object> resultObj = new HashMap();
        String APP_VERSION = sysConfigService.getValue("APP_VERSION","");
        String APP_DOWNLOAD = sysConfigService.getValue("APP_DOWNLOAD","");
        resultObj.put("APP_VERSION", APP_VERSION);
        resultObj.put("APP_DOWNLOAD", APP_DOWNLOAD);
        return toResponsSuccess(resultObj);
    }

    /**
     * 获取当前会员银行账户
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取当前会员银行账户")
    @RequestMapping("getUserAccount")
    public Object getUserAccount(@LoginUser UserVo loginUser) {
        List<UserAccountVo> userAccounts = userAccountService.queryByUserId(loginUser.getUserId());
        return toResponsSuccess(userAccounts);
    }
    /**
     * 添加会员银行账户
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "添加会员银行账户")
    @RequestMapping("addUserAccount")
    public Object addUserAccount(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String bankName = jsonParams.getString("bankName");
        String userName = jsonParams.getString("uaerName");
        String account = jsonParams.getString("account");
        String bankCode = jsonParams.getString("bankCode");
        String cardType = jsonParams.getString("cardType");
        String cardTypeName = jsonParams.getString("cardTypeName");
        String openingBank = jsonParams.getString("openingBank");
        if(StringUtils.isNullOrEmpty(userName)||StringUtils.isNullOrEmpty(account)||StringUtils.isNullOrEmpty(openingBank)){
            return toResponsFail("请求数据不能为空");
        }
        if(StringUtils.isNullOrEmpty(bankCode)||StringUtils.isNullOrEmpty(cardType)||StringUtils.isNullOrEmpty(cardTypeName)){
            return toResponsFail("请求数据不能为空");
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", loginUser.getUserId());
        param.put("account", account);
        List<UserAccountVo> userAccounts = userAccountService.queryList(param);
        if(userAccounts!=null && userAccounts.size()>0){
            UserAccountVo userAccount = userAccounts.get(0);
            if(userAccount.getStatus().equals("0")){
                userAccount.setStatus("1");
                int userAccountIndex = userAccountService.update(userAccount);
                return toResponsSuccess(userAccountIndex);
            }else{
                return toResponsFail("已添加，无需重复操作");
            }
        }
        if(StringUtils.isNullOrEmpty(bankName)){
            String bank = accountService.queryByBankCode(bankCode);
            if(StringUtils.isNullOrEmpty(bank)){
                return toResponsFail("请联系管理员");
            }
            bankName = bank;
        }
        UserAccountVo userAccountVo = new UserAccountVo();
        userAccountVo.setUser_id(loginUser.getUserId());
        userAccountVo.setBank_name(bankName);
        userAccountVo.setUser_name(userName);
        userAccountVo.setAccount(account);
        userAccountVo.setOpening_bank(openingBank);
        userAccountVo.setBank_code(bankCode);
        userAccountVo.setCard_type(cardType);
        userAccountVo.setCard_type_name(cardTypeName);
        userAccountVo.setApp_time(new Date());
        userAccountVo.setStatus("1");
        int accountIndex = userAccountService.save(userAccountVo);
        if(accountIndex!=1){
            return toResponsFail("请稍后重试");
        }
        return toResponsSuccess(accountIndex);
    }

    /**
     * 获取笑笑宝银行账户
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取笑笑宝银行账户")
    @RequestMapping("getXiaoxiaoAccount")
    public Object getXiaoxiaoAccount(@LoginUser UserVo loginUser) {
        Long xiaoxiaoId = new Long(1);
        List<UserAccountVo> userAccounts = userAccountService.queryByUserId(xiaoxiaoId);
        return toResponsSuccess(userAccounts);
    }

}
